package com.tangyee.person_risk_assessment.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tangyee.person_risk_assessment.StartRiskAssessmentActivity;
import com.tangyee.person_risk_assessment.adapter.OptionsListAdapter;
import com.tangyee.person_risk_assessment.view.AssessViewPager;
import com.tangyee.R;

import com.tangyee.person_risk_assessment.StartRiskAssessmentActivity;
import com.tangyee.person_risk_assessment.adapter.OptionsListAdapter;
import com.tangyee.person_risk_assessment.bean.OptionScoreBean;
import com.tangyee.person_risk_assessment.bean.QuestionBean;
import com.tangyee.person_risk_assessment.data.UserHeight;
import com.tangyee.person_risk_assessment.data.UserWeight;
import com.tangyee.person_risk_assessment.view.AssessViewPager;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AssessFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AssessFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "param3";

    // TODO: Rename and change types of parameters
    private QuestionBean questionBean;
    // 每一道题选项对应的分数
    private OptionScoreBean optionScoreBean;

    private View view;
    private OptionsListAdapter optionsListAdapter;
    private ListView listView;
    private AssessViewPager assessViewPager;
    private TextView lastFragment;
    private TextView nextFragment;

    // 用作回调的,创建身高和体重的接口
    private NewPickerDialog pickerDialog;

    //
    private int currentNumber;
    private int allNumber;

    public AssessFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     * @return A new instance of fragment ReadFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AssessFragment newInstance(QuestionBean questionBean, int currentNumber, int allNumber) {
        AssessFragment fragment = new AssessFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, questionBean);
        args.putSerializable(ARG_PARAM2, currentNumber);
        args.putSerializable(ARG_PARAM3, allNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            questionBean = (QuestionBean) getArguments().getSerializable(ARG_PARAM1);
            currentNumber = (int) getArguments().getSerializable(ARG_PARAM2);
            allNumber = (int) getArguments().getSerializable(ARG_PARAM3);
        }

        view = getActivity().getLayoutInflater().inflate(R.layout.fragment_assess, null);

        initView();


    }

    // 滑过时,以前的fragment 并没有真正销毁，利用这一特性，我将初始化视图放在 onCreate 里面，没有放在这里面
    // 详解 https://www.cnblogs.com/laishenghao/p/5157914.html
    // (但是很奇怪，我一开始是没有把视图的初始化放在 onCreate 的，但fragment 滑到以前的，也是没有重新加载的视图
    // 因此我猜想，fragment 的销毁与时间、内存也有一定关系)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        view = inflater.inflate(R.layout.fragment_assess, container, false);
//
//        initView();

        return view;
    }

    public AssessViewPager getAssessViewPager() {
        return assessViewPager;
    }

    public void setAssessViewPager(AssessViewPager assessViewPager) {
        this.assessViewPager = assessViewPager;
    }

    public OptionScoreBean getOptionScoreBean() {
        return optionScoreBean;
    }

    public void setOptionScoreBean(OptionScoreBean optionScoreBean) {
        this.optionScoreBean = optionScoreBean;
    }

    public NewPickerDialog getPickerDialog() {
        return pickerDialog;
    }

    public void setPickerDialog(NewPickerDialog pickerDialog) {
        this.pickerDialog = pickerDialog;
    }

    public interface NewPickerDialog{
        public void showHeightPickerDialog();
    }

    private void initView() {
        System.out.println((currentNumber +1 ) + "/" + allNumber);

        TextView questionTitleText = view.findViewById(R.id.assess_question);
        TextView currentNumberText = view.findViewById(R.id.current_number);
        TextView allNumberText = view.findViewById(R.id.all_number);

        questionTitleText.setText(questionBean.getQuestionTitle());
        currentNumberText.setText((currentNumber + 1) + "");
        allNumberText.setText("/" + allNumber);

        listView = view.findViewById(R.id.assess_listview);
        optionsListAdapter = new OptionsListAdapter(getActivity(), questionBean.getQuestionOptionList(), listView, StartRiskAssessmentActivity.userQuestionOption[currentNumber]);
        if(currentNumber == allNumber - 1){ // 是最后一个问题就不要默认有勾
            optionsListAdapter.setFinalQuestion(true);
        }
        listView.setAdapter(optionsListAdapter);
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        /**
         * 这里用的监听是new AdapterView.OnItemClickListener(),能监听得到item的属性，但在这里面对 listView 里的item 进行改变，没有效果
         * 所以须在 OptionsListAdapter 里对item 进行状态的改变
         */
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 如果不是最后一题，那么点击一个item 就得刷新，改变勾的位置
                optionsListAdapter.notifyDataSetChanged();
                TextView textView = view.findViewById(R.id.option_text);
                System.out.println(textView.getText());

                // 如果当前是最后一题（fragment），即身高体重题
                if(currentNumber == allNumber - 1){
                    if(position == 0){ // 如果点击的是第一个item ,即身高
                        // 这个是根据回调函数来创建dialog
//                        getPickerDialog().showHeightPickerDialog();
                        getHeightDialog();
                    }else { // 如果点击的是第二个item，即体重
                        getWeightDialog();
                    }
                }

                // 更新listView 点击的item 的position
                optionsListAdapter.setCheckedPosition(position);
                // 针对点击的item 评定一个分数
                assessResultScore(position);

            }
        });

        // 上一题的点击事件
        lastFragment = view.findViewById(R.id.last_fragment);
        lastFragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentItem = getAssessViewPager().getCurrentItem();
                currentItem = currentItem - 1;
                if (currentItem > allNumber - 1){
                    currentItem = allNumber - 1;
                }
                getAssessViewPager().setCurrentItem(currentItem,true);
            }
        });
        // 下一题的点击事件
        nextFragment = view.findViewById(R.id.next_fragment);
        nextFragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentItem = getAssessViewPager().getCurrentItem();
                currentItem = currentItem + 1;
                if (currentItem < 0){
                    currentItem = 0;
                }
                getAssessViewPager().setCurrentItem(currentItem,true);
            }
        });

    }

    private void getHeightDialog(){
        UserHeightPickerDialog.newInstance(UserHeightPickerDialog.TYPE_DIALOG, new ActionListener() {
            @Override
            public void onCancelClick(BaseDialogFragment dialog) {

            }

            @Override
            public void onDoneClick(BaseDialogFragment dialog) {
                UserHeight userHeight = ((UserHeightPickerDialog)dialog).getSelectedItem();
                StartRiskAssessmentActivity.userQuestionHeight = userHeight.getHeight();
                optionsListAdapter.notifyDataSetChanged();
                assessResultScore(-1);
                Toast.makeText(getActivity(), userHeight.getHeight()+"", Toast.LENGTH_SHORT).show();
            }
        }).show(getActivity().getFragmentManager(), "dialog");
    }

    private void getWeightDialog(){
        UserWeightPickerDialog.newInstance(UserHeightPickerDialog.TYPE_DIALOG, new ActionListener() {
            @Override
            public void onCancelClick(BaseDialogFragment dialog) {

            }

            @Override
            public void onDoneClick(BaseDialogFragment dialog) {
                UserWeight userWeight = ((UserWeightPickerDialog)dialog).getSelectedItem();
                StartRiskAssessmentActivity.userQuestionWeight = userWeight.getWeight();
                optionsListAdapter.notifyDataSetChanged();
                assessResultScore(-1);
                Toast.makeText(getActivity(), userWeight.getWeight() + "", Toast.LENGTH_SHORT).show();
            }
        }).show(getActivity().getFragmentManager(), "dialog");
    }

    private void assessResultScore(int position){
        // 如果当前的问题（fragment）不是最后一题
        if(currentNumber != allNumber - 1){
            int[] optionScore = getOptionScoreBean().getOptionScore();
            StartRiskAssessmentActivity.userAnswerScore[currentNumber] = optionScore[position];
            StartRiskAssessmentActivity.userQuestionOption[currentNumber] = optionsListAdapter.getCheckedPosition();
            System.out.println("分数" + optionScore[position]);
        }else {
            // 若为最后一题，即身高与体重题，则根据公式来评定分数
            if(StartRiskAssessmentActivity.userQuestionHeight != -1 && StartRiskAssessmentActivity.userQuestionWeight != -1) {
                int score = StartRiskAssessmentActivity.userAnswerScore[currentNumber] = getOptionScoreBean().getBMIAssessScore(
                        StartRiskAssessmentActivity.userQuestionWeight,
                        StartRiskAssessmentActivity.userQuestionHeight
                );
                System.out.println("分数" + score);
            }
        }
    }

}

